<script setup lang="ts">
import { useAuthStore } from '@/stores/auth'
import { onMounted, ref, computed, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import AppHeader from '@/components/layout/AppHeader.vue'
import LeftSidebar from '@/components/layout/LeftSidebar.vue'
import PopupModal from '@/components/common/PopupModal.vue'
import { type HomeSection, HOME_SECTIONS } from '@/constants/HOME'
import { api, toAbsoluteUrl } from '@/utils/request'

const auth = useAuthStore()
const router = useRouter()

const liveRooms = ref<any[]>([])
const loading = ref(false)
const loadingMore = ref(false)
const currentSection = ref<HomeSection>(HOME_SECTIONS.HOME)

// 分页相关状态
const currentPage = ref(1)
const totalRooms = ref(0)
const hasMoreRooms = ref(true)

// 弹窗状态管理
const showPopup = ref(false)

onMounted(async () => {
  // 尝试获取用户信息，但不强制要求登录
  if (!auth.user) {
    await auth.fetchMe()
  }

  await fetchLiveRooms()
  await fetchAdvertisements()

  // 检查是否需要显示弹窗（首次访问或者用户设置）
  const today = new Date().toDateString()
  const lastShown = localStorage.getItem('client_popup-last-shown')

  if (lastShown !== today) {
    // 延迟一点显示弹窗，让页面先加载完成
    setTimeout(() => {
      showPopup.value = true
      localStorage.setItem('client_popup-last-shown', today)
    }, 500)
  }
})

const fetchLiveRooms = async (page = 1, append = false) => {
  if (page === 1) {
    loading.value = true
  } else {
    loadingMore.value = true
  }

  try {
    const response = await api.get(`/api/live/rooms?page=${page}&limit=20`)
    const data = await response.json()

    if (append) {
      // 追加到现有列表
      liveRooms.value = [...liveRooms.value, ...(data.liveRooms || [])]
    } else {
      // 替换整个列表
      liveRooms.value = data.liveRooms || []
    }

    totalRooms.value = data.total || 0
    currentPage.value = page
    hasMoreRooms.value = liveRooms.value.length < totalRooms.value
  } catch (error) {
    console.error('라이브 방 목록 가져오기 실패:', error)
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

const enterLiveRoom = (room: any) => {
  // 检查是否已登录，未登录则跳转到登录页面
  if (!auth.user) {
    router.push('/login')
    return
  }
  router.push(`/live/${room.id}`)
}

const getViewerCount = (room: any) => {
  return room.manualViewerCount || 0
}

// 加载更多房间
const loadMoreRooms = async () => {
  if (!hasMoreRooms.value || loadingMore.value) return
  await fetchLiveRooms(currentPage.value + 1, true)
}

// 顶部轮播相关（使用广告数据）
const advertisements = ref<any[]>([])
const currentSlide = ref(0)
let autoplayTimer: any = null

// 获取活跃广告
const fetchAdvertisements = async () => {
  try {
    const res = await api.get('/api/content/advertisements')
    if (res.ok) {
      const data = await res.json()
      advertisements.value = data.advertisements || []
      startAutoplay()
    }
  } catch (error) {
    console.error('获取广告失败:', error)
  }
}

const startAutoplay = () => {
  if (autoplayTimer) clearInterval(autoplayTimer)
  if (!advertisements.value.length) return
  autoplayTimer = setInterval(() => {
    currentSlide.value = (currentSlide.value + 1) % advertisements.value.length
  }, 3500)
}

onUnmounted(() => {
  if (autoplayTimer) clearInterval(autoplayTimer)
})

const nextSlide = () => {
  if (!advertisements.value.length) return
  currentSlide.value = (currentSlide.value + 1) % advertisements.value.length
}

const prevSlide = () => {
  if (!advertisements.value.length) return
  currentSlide.value = (currentSlide.value - 1 + advertisements.value.length) % advertisements.value.length
}

const goToSlide = (idx: number) => {
  if (!advertisements.value.length) return
  currentSlide.value = idx
}

const slideClass = (idx: number) => {
  const len = advertisements.value.length
  if (idx === currentSlide.value) return 'active'
  if (idx === (currentSlide.value - 1 + len) % len) return 'prev'
  if (idx === (currentSlide.value + 1) % len) return 'next'
  return 'hidden'
}

// 处理广告点击
const handleAdvertisementClick = async (ad: any) => {
  try {
    // 记录点击
    await api.post(`/api/content/advertisements/${ad.id}/click`)

    // 如果有链接URL，则打开链接
    if (ad.linkUrl) {
      window.open(ad.linkUrl, '_blank')
    }
  } catch (error) {
    console.error('记录广告点击失败:', error)
    // 即使记录失败，也要打开链接
    if (ad.linkUrl) {
      window.open(ad.linkUrl, '_blank')
    }
  }
}
</script>

<template>
  <div class="layout">
    <AppHeader />
    <div class="main">
      <LeftSidebar v-model="currentSection" />
      <div class="content">
        <div class="carousel" v-if="advertisements.length">
          <button class="nav prev" @click="prevSlide">‹</button>
          <div class="track">
            <div
              v-for="(ad, idx) in advertisements"
              :key="ad.id"
              class="slide"
              :class="slideClass(idx)"
              @click="handleAdvertisementClick(ad)"
              :title="ad.title"
            >
              <img
                class="slide-img"
                :src="toAbsoluteUrl(ad.imageUrl) || 'https://picsum.photos/960/360'"
                :alt="ad.title"
              />
              <div class="slide-mask">
                <div class="slide-meta">
                  <div class="slide-title">{{ ad.title }}</div>
                  <div class="slide-sub" v-if="ad.description">{{ ad.description }}</div>
                </div>
              </div>
            </div>
          </div>
          <button class="nav next" @click="nextSlide">›</button>
          <div class="dots">
            <button
              v-for="(ad, i) in advertisements"
              :key="ad.id + '-dot'"
              class="dot"
              :class="{ active: i === currentSlide }"
              @click="goToSlide(i)"
            />
          </div>
        </div>

        <div class="live-header">
          <h2>LIVE NOW</h2>
          <p>현재 라이브 중인 방 ({{ liveRooms.length }}{{ totalRooms > 0 ? ` / ${totalRooms}` : '' }}개)</p>
        </div>

        <div class="live-grid" v-loading="loading">
          <div
            v-for="room in liveRooms"
            :key="room.id"
            class="live-card"
            @click="enterLiveRoom(room)"
          >
            <div class="live-preview">
              <img
                :src="toAbsoluteUrl(room.coverUrl) || toAbsoluteUrl(room.replayVideo?.coverUrl) || 'https://picsum.photos/320/180'"
                :alt="room.title || room.channel.name"
                class="preview-image"
              />
              <div class="live-badge">LIVE</div>
              <div class="viewer-count">{{ getViewerCount(room) }}</div>
            </div>

            <div class="live-info">
              <div class="channel-avatar">
                <img
                  :src="toAbsoluteUrl(room.channel.avatarUrl) || 'https://picsum.photos/40'"
                  :alt="room.channel.name"
                />
              </div>
              <div class="live-details">
                <h3 class="live-title">{{ room.title || room.channel.name }}</h3>
                <p class="channel-name">{{ room.channel.name }}</p>
                <div class="live-tags">
                  <span class="tag">라이브</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 加载更多按钮 -->
        <div v-if="!loading && liveRooms.length > 0 && hasMoreRooms" class="load-more-section">
          <button
            class="load-more-btn"
            @click="loadMoreRooms"
            :disabled="loadingMore"
          >
            <span v-if="loadingMore">로딩 중...</span>
            <span v-else>더 많은 방 보기 ({{ totalRooms - liveRooms.length }}개 더)</span>
          </button>
        </div>

        <div v-if="!loading && liveRooms.length === 0" class="empty-state">
          <p>라이브 방이 없습니다</p>
        </div>
      </div>
    </div>

    <!-- 弹窗组件 -->
    <PopupModal v-model="showPopup" />
  </div>
</template>

<style scoped>
.layout {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--color-bg);
}

.main {
  flex: 1;
  display: flex;
  min-height: 0;
}

.content {
  flex: 1;
  padding: var(--space-5);
  overflow-y: auto;
  background: var(--color-surface);
}

.live-header {
  margin-bottom: var(--space-6);
}

.live-header h2 {
  color: var(--color-text);
  font-size: 32px;
  margin: 0 0 var(--space-2) 0;
  font-weight: 700;
}

.live-header p {
  color: var(--color-text-secondary);
  margin: 0;
  font-size: 16px;
}

.live-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: var(--space-5);
}

.live-card {
  background: var(--color-bg);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-lg);
  overflow: hidden;
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: var(--shadow-sm);
}

.live-card:hover {
  transform: translateY(-4px);
  box-shadow: var(--shadow-lg);
  border-color: var(--color-primary);
}

.live-preview {
  position: relative;
  width: 100%;
  height: 180px;
  overflow: hidden;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.2s ease;
}

.live-card:hover .preview-image {
  transform: scale(1.05);
}

.live-badge {
  position: absolute;
  top: var(--space-3);
  left: var(--space-3);
  background: var(--gradient-primary);
  color: var(--color-text-white);
  padding: var(--space-1) var(--space-2);
  border-radius: var(--radius-sm);
  font-size: 12px;
  font-weight: 700;
  box-shadow: var(--shadow-sm);
}

.viewer-count {
  position: absolute;
  bottom: var(--space-3);
  right: var(--space-3);
  background: rgba(0, 0, 0, 0.7);
  color: var(--color-text-white);
  padding: var(--space-1) var(--space-2);
  border-radius: var(--radius-sm);
  font-size: 12px;
  font-weight: 600;
  backdrop-filter: blur(4px);
}

.live-info {
  padding: var(--space-4);
  display: flex;
  gap: var(--space-3);
}

.channel-avatar {
  flex-shrink: 0;
}

.channel-avatar img {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid var(--color-border);
}

.live-details {
  flex: 1;
  min-width: 0;
}

.live-title {
  color: var(--color-text);
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 var(--space-1) 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.channel-name {
  color: var(--color-text-secondary);
  font-size: 14px;
  margin: 0 0 var(--space-2) 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.live-tags {
  display: flex;
  gap: var(--space-2);
}

.tag {
  background: var(--color-primary-light);
  color: var(--color-primary);
  padding: var(--space-1) var(--space-2);
  border-radius: var(--radius-sm);
  font-size: 11px;
  font-weight: 600;
  border: 1px solid var(--color-border);
}

.empty-state {
  text-align: center;
  color: var(--color-text-muted);
  padding: var(--space-6) var(--space-5);
}

.empty-state p {
  font-size: 18px;
  margin: 0;
}

/* 加载更多按钮样式 */
.load-more-section {
  text-align: center;
  margin-top: var(--space-6);
  padding: var(--space-4);
}

.load-more-btn {
  background: var(--color-primary);
  color: var(--color-text-white);
  border: none;
  padding: var(--space-3) var(--space-6);
  border-radius: var(--radius-lg);
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: var(--shadow-sm);
  min-width: 200px;
}

.load-more-btn:hover:not(:disabled) {
  background: var(--color-primary-dark);
  transform: translateY(-2px);
  box-shadow: var(--shadow-md);
}

.load-more-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

/* Loading 样式 */
.live-grid[v-loading] {
  min-height: 200px;
}

/* 顶部轮播样式 */
.carousel {
  position: relative;
  width: 100%;
  height: 360px;
  margin-bottom: var(--space-6);
  border-radius: var(--radius-xl);
  overflow: hidden;
}

.carousel .track {
  position: absolute;
  inset: 0;
  display: grid;
}

.carousel .slide {
  position: absolute;
  top: 50%;
  left: 50%;
  width: min(960px, 85%);
  height: 100%;
  transform: translate(-50%, -50%);
  border-radius: var(--radius-xl);
  overflow: hidden;
  transition: transform 0.4s ease, opacity 0.4s ease, filter 0.4s ease;
  cursor: pointer;
  box-shadow: var(--shadow-lg);
}

.carousel .slide.hidden {
  opacity: 0;
  pointer-events: none;
  transform: translate(-50%, -50%) scale(0.8);
  filter: blur(2px);
  z-index: 0;
}

.carousel .slide.prev {
  opacity: 0.7;
  transform: translate(calc(-50% - 260px), -50%) scale(0.9);
  filter: blur(1px);
  z-index: 1;
}

.carousel .slide.next {
  opacity: 0.7;
  transform: translate(calc(-50% + 260px), -50%) scale(0.9);
  filter: blur(1px);
  z-index: 1;
}

.carousel .slide.active {
  opacity: 1;
  transform: translate(-50%, -50%) scale(1);
  z-index: 3;
}

.carousel .slide-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.carousel .slide-mask {
  position: absolute;
  inset: 0;
  background: linear-gradient(0deg, rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.1) 60%);
  pointer-events: none;
}

.carousel .slide-meta {
  position: absolute;
  left: var(--space-5);
  bottom: var(--space-5);
  color: var(--color-text-white);
}

.carousel .slide-title {
  font-size: 24px;
  font-weight: 700;
  margin-bottom: var(--space-1);
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
}

.carousel .slide-sub {
  opacity: 0.9;
  font-size: 16px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}

.carousel .nav {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background: rgba(255, 255, 255, 0.9);
  color: var(--color-text);
  border: none;
  width: 48px;
  height: 48px;
  border-radius: 50%;
  cursor: pointer;
  z-index: 10;
  font-size: 20px;
  font-weight: bold;
  transition: all 0.2s ease;
  backdrop-filter: blur(4px);
}

.carousel .nav:hover {
  background: var(--color-bg);
  color: var(--color-primary);
  transform: translateY(-50%) scale(1.1);
}

.carousel .nav.prev {
  left: var(--space-3);
}

.carousel .nav.next {
  right: var(--space-3);
}

.carousel .dots {
  position: absolute;
  left: 0;
  right: 0;
  bottom: var(--space-4);
  display: flex;
  justify-content: center;
  gap: var(--space-2);
}

.carousel .dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.5);
  border: none;
  cursor: pointer;
  transition: all 0.2s ease;
}

.carousel .dot:hover {
  background: rgba(255, 255, 255, 0.8);
  transform: scale(1.2);
}

.carousel .dot.active {
  background: var(--color-text-white);
  transform: scale(1.3);
}

/* 移动端响应式设计 */
@media (max-width: 768px) {
  .content {
    padding: var(--space-4);
  }

  .live-header h2 {
    font-size: 24px;
  }

  .live-header p {
    font-size: 14px;
  }

  .live-grid {
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: var(--space-4);
  }

  .load-more-btn {
    font-size: 14px;
    padding: var(--space-2) var(--space-4);
    min-width: 160px;
  }

  .carousel {
    height: 240px;
    margin-bottom: var(--space-4);
  }

  .carousel .slide {
    width: min(90%, 600px);
  }

  .carousel .slide-title {
    font-size: 18px;
  }

  .carousel .slide-sub {
    font-size: 14px;
  }

  .carousel .nav {
    width: 40px;
    height: 40px;
    font-size: 18px;
  }

  .carousel .nav.prev {
    left: var(--space-2);
  }

  .carousel .nav.next {
    right: var(--space-2);
  }

  .live-preview {
    height: 160px;
  }

  .live-info {
    padding: var(--space-3);
  }

  .channel-avatar img {
    width: 40px;
    height: 40px;
  }

  .live-title {
    font-size: 15px;
  }

  .channel-name {
    font-size: 13px;
  }
}

@media (max-width: 480px) {
  .layout {
    padding-bottom: 80px; /* 为底部导航留出空间 */
  }

  .main {
    /* 在手机端，侧边栏变成固定定位，所以主内容区域占满宽度 */
    display: block;
  }

  .content {
    padding: var(--space-3);
  }

  .live-header {
    margin-bottom: var(--space-4);
    text-align: center;
  }

  .live-header h2 {
    font-size: 20px;
  }

  .live-grid {
    grid-template-columns: 1fr;
    gap: var(--space-3);
  }

  .carousel {
    height: 200px;
    margin-bottom: var(--space-3);
  }

  .carousel .slide {
    width: 95%;
  }

  .carousel .slide.prev,
  .carousel .slide.next {
    display: none; /* 小屏幕上隐藏侧边预览 */
  }

  .carousel .slide-title {
    font-size: 16px;
  }

  .carousel .slide-sub {
    font-size: 13px;
  }

  .carousel .nav {
    width: 36px;
    height: 36px;
    font-size: 16px;
  }

  .carousel .dot {
    width: 10px;
    height: 10px;
  }

  .live-card {
    border-radius: var(--radius-md);
  }

  .live-preview {
    height: 180px;
  }

  .live-info {
    padding: var(--space-3);
    gap: var(--space-2);
  }

  .channel-avatar img {
    width: 36px;
    height: 36px;
  }

  .live-title {
    font-size: 14px;
  }

  .channel-name {
    font-size: 12px;
  }

  .tag {
    font-size: 10px;
    padding: 2px var(--space-1);
  }

  .live-badge {
    font-size: 11px;
    padding: 2px var(--space-1);
  }

  .viewer-count {
    font-size: 11px;
    padding: 2px var(--space-1);
  }

  .load-more-section {
    margin-top: var(--space-4);
    padding: var(--space-3);
  }

  .load-more-btn {
    font-size: 13px;
    padding: var(--space-2) var(--space-3);
    min-width: 140px;
  }
}
</style>
